/**
 * Created by apple on 2016/12/8.
 */

var express = require('express');
var router = express.Router();
var url = require('url');
var Appo = require('../models').Appointment;
var Outcall = require('../models').Outcall;
var Doctor = require('../models').Doctor;
var Hospital = require('../models').Hospital;
var Department = require('../models').Department;
var Payment = require('../models').Payment;
var User = require('../models').User;
var async = require('async');

/*
* 我的预约的界面的GET HTTP 请求的处理方法 */
router.get('/my',function(req, res,next){
    var user = req.session.user;
    if (user !== undefined) { //用户已登陆
        var list_myAppointment = [];
        var list_myDoctor = [];
        var list_myWallet = [];
        async.waterfall([function (callback) {
            Appo.findByUser(user.id).then(function (list_appo_f) {
                callback(null, list_appo_f);
            });
        },function (list_appo_f, callback) {
            //处理我的预约表
            async.each(list_appo_f, function (item, callback) {
                var oc_id = item.dataValues.Outcall_id;

			    Outcall.findById(oc_id).then(function (oc_f) {
				    return Doctor.findById(oc_f.doc_id);
			    }).then(function (doc_f) {
				    var doctor_name = doc_f.name;
				    var doctor_id = doc_f.id;
				    var doctor_hp = doc_f.hp_id;
				    var doctor_dpt = doc_f.dpt_id;
				    var doc_hp_name;
				    var doc_dpt_name;
				    //如果list_myDoctor中不包含当前医生，则把当前医生添加到list_myDoctor中
				    var i;
				    for (i = 0; i < list_myDoctor.length; i++) {
					    if (list_myDoctor[i].doctorID === doctor_id) {
						    break;
					    }
				    }
				    if (i === list_myDoctor.length) {
					    Hospital.findById(doctor_hp).then(function (hp_f) {
						    doc_hp_name = hp_f.name;
						    return Department.findById(doctor_dpt);
					    }).then(function (dpt_f) {
						    doc_dpt_name = dpt_f.name;
						    list_myDoctor.push({
							    doctorID: doctor_id,
							    doctorName: doctor_name,
							    belongHospital: doc_hp_name,
							    belongDepartment: doc_dpt_name,
							    patientReview: "Good"
						    });
					    });
				    }

				    var appoTime = item.dataValues.createTime.getFullYear() + '年' + (item.dataValues.createTime.getMonth() + 1) + '月' + item.dataValues.createTime.getDate() + '日 '
					    + item.dataValues.createTime.getHours() + '时' + item.dataValues.createTime.getMinutes() + '分';

				    list_myAppointment.push({
					    appointmentID: item.dataValues.id,
					    appointmentDoctor: doctor_name,
					    appointmentTime: appoTime,
					    appointmentState: item.dataValues.Status
				    });
				    callback(null);
			    });
		    }, function (err, result) {
			    callback(null);
		    });
	    }, function (callback) {
		    Payment.findByUser(user.id).then(function (list_pay_f) {
			    async.each(list_pay_f, function (item, callback) {
				    var pay_time = item.dataValues.createTime.getFullYear() + '年' + (item.dataValues.createTime.getMonth() + 1) + '月' + item.dataValues.createTime.getDate() + '日 '
					    + item.dataValues.createTime.getHours() + '时' + item.dataValues.createTime.getMinutes() + '分';
				    var pay_amount = item.dataValues.fee;
				    var pay_hp = item.dataValues.hp_id;
				    var pay_hp_name;

				    Hospital.findById(pay_hp).then(function (hp_f) {
					    pay_hp_name = hp_f.name;

					    list_myWallet.push({
						    payTime: pay_time,
						    payAmount: pay_amount,
						    payHospital: pay_hp_name
					    });
					    callback(null);
				    });
			    }, function (err, result) {
				    callback(null);
			    });
		    });
	    }, function (callback) {
		    User.findById(req.session.user.id).then(function (user_f) {
			    user = user_f;
			    callback(null);
		    });
	    }
	    ], function (err, result) {
		    res.render('user/myappointment', {
			    user: user,
			    title: req.session.user.name.toString() + '预约记录',
			    myAppointment: list_myAppointment.sort(function (a, b) {
				    return (a.appointmentTime < b.appointmentTime);
			    }),
			    myDoctor: list_myDoctor.sort(function (a, b) {
				    return (a.doctorID > b.doctorID);
			    }),
			    myWallet: list_myWallet.sort(function (a, b) {
				    return (a.payTime < b.payTime);
			    })
		    });
	    });
    }
    else {
        res.redirect('/user/login');
    }
}).post('/my',function (req, res, next) {
    var appo_id = +req.body.appointmentID;
    Appo.findById(appo_id).then(function (appointment) {
        var oc_id = appointment.Outcall_id;
        appointment.destroy();
        return Outcall.findById(oc_id);
    }).then(function (outcall) {
        outcall.increment({'Remain': 1});
        res.json({
            user:req.session.user
        });
    });
    // Appo.destroy({
    //     where: {id:appo_id}
    // }).then(function (appo) {
    //     if(appo) {
    //
		// 	res.json({
		// 		user:req.session.user
		// 	})
    //     }
    // });
});

module.exports = router;